<template>
  <div>
    <!-- <el-upload
            class="upload-demo"
            :action="actionUrl"
            :on-change="handleFileChange"
            :before-upload="handleBeforeUpload"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-error="handleUploadError"
            :file-type="['.pdf']"
            :file-list="scope.row.fileList">
            <el-button size="small" type="primary" plain>点击上传</el-button>
        </el-upload> -->
    <span style="color: #666; margin-bottom: 10px;">
      <!-- <span style="color: red;">*</span>  -->
      请上传{{ fileType.join('、') }}格式文件</span>
    <el-table
      :data="tableData"
      align="center"
      style="width: 100%;margin-top: 10px;"
    >
      <el-table-column prop="annexName" label="资料名称" align="center" />
      <el-table-column prop="date" label="上传文件" width="180" align="center">
        <template slot-scope="scope">
          <el-upload
            class="upload-demo"
            :action="actionUrl"
            :headers="headers"
            :on-change="handleFileChange"
            :before-upload="handleBeforeUpload"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
          >
            <el-button :disabled="disabled" size="small" type="primary" plain @click="handleUnload(scope.$index)">点击上传</el-button>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="danger" :disabled="disabled" @click="handleDelete(scope.$index)">删除</el-button>
          <el-button v-if="disabled" @click="handleDown(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: center;margin: 20px 0;">
      <el-button type="primary" :disabled="disabled" @click="handleAddRow">+新增</el-button>
    </div>
  </div>
</template>
<script>
import { updateNewsStudyTypeSort } from '@/api/content-manage/researchResult.js'
import { getToken } from '@/utils/auth'
import { updateMessageTypeSort } from '@/api/inner-msg/index.js'
import FormGroup from '@/views/components/FormGroup'
export default {
  name: 'DragSrot',
  components: { FormGroup },
  props: {
    value: {
      type: Array,
      default: () => { return [] }
    },
    fileType: {
      type: Array,
      default: () => { return ['.pdf', '.zip'] }
    },
    fileSize: {
      type: Number,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      headers: { Authorization: 'Bearer ' + getToken() }, // 设置上传的请求头部
      actionUrl: `${process.env.VUE_APP_BASE_API + (process.env.NODE_ENV === 'development' ? 'admin-api-test/' : 'admin-api/')}infra/file/upload`,
      // actionUrl: process.env.VUE_APP_BASE_API + "/app-api/student/web-student/upload",
      tableData: [
        {
          annexName: '',
          annexUrl: ''
        }
      ],
      currentFileIndex: -1
    }
  },
  watch: {
    value: {
      deep: true,
      handler(val) {
        this.tableData = JSON.parse(JSON.stringify(val)) || []
      }
    }
  },
  methods: {
    handleClose() {
      this.dialogVisible = false
      this.tableList = []
    },
    open() {
      this.dialogVisible = true
    },
    handleAddRow() {
      if (!Array.isArray(this.tableData)) {
        this.tableData = []
      }
      this.tableData.push({
        fileList: [],
        annexName: '',
        annexUrl: ''
      })
    },
    handleUnload(index) {
      console.log(index, '----当前点击的行')
      this.currentFileIndex = index
    },

    handleFileChange() {},

    handleBeforeUpload(file) {
      const fileTypeList = this.fileType.map(v => {
        return v.slice(1)
      })
      let isAble = false

      fileTypeList.forEach(v => {
        if (file.type.indexOf(v) > -1) {
          isAble = true
        }
      })
      console.log(fileTypeList, file.type, '----file---')
      if (!isAble) {
        this.$modal.msgError(`请上传${this.fileType.join('/')}文件`)
        return false
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      return true
    },

    handleFileUploadProgress() {},

    // 上传成功回调
    handleFileSuccess(res, file) {
      console.log(res, file, '----上传结果')
      // this.$refs.upload.clearFiles()
      // // 清理
      // this.upload.isUploading = false
      // this.$modal.closeLoading()
      // 如果上传成功
      if (res.code === 0) {
        this.tableData[this.currentFileIndex].annexName = file.name
        this.tableData[this.currentFileIndex].annexUrl = res.data
        this.handleTransferFileList(this.tableData)
      } else {
        this.$modal.msgError(res.msg)
      }
    },
    handleTransferFileList(tableData) {
      this.tableData.splice(1000, 0)
      const ableList = tableData.filter(v => {
        return v.annexName && v.annexUrl
      })
      if (!ableList || ableList.length === 0) {
        this.$emit('input', [])
        rturn
      }
      const list = ableList.map(v => {
        return {
          'annexName': v.annexName,
          'annexUrl': v.annexUrl,
          'id': v.id || null,
          'relationId': v.relationId || null,
          'relationType': v.relationType || null

        }
      })
      this.$emit('input', list)
    },

    handleUploadError() {
      this.$modal.msgError('上传文件失败，请重试')
      this.$modal.closeLoading()
    },

    // 点击删除按钮
    handleDelete(index) {
      this.tableData.splice(index, 1)
      this.$emit('input', this.tableData)
    },
    handleDown(row) {
      if (row.annexUrl) {
        window.open(row.annexUrl, '_blank')
      }
    },
    // 上传文件
    handleChange(data) {

    },
    async handleConfirm() {
      const ids = this.tableList.map(v => v.id)
      const { code, msg } = await updateMessageTypeSort({
        ids
      })
      if (code !== 0) {
        this.$message.error(msg)
        return
      }
      this.handleClose()
      this.$emit('success')
    }
  }
}
</script>

<style lang="scss" scoped>
    .title-list {
        background:#fff;
        margin:100px auto 0;
        border: 1px solid red;

        .audit-project {

        }
        .dialog-footer {
            margin-top: 20px;
            text-align: center;
        }

    }
</style>
